#!/usr/bin/python
#
# absynth.py
# Copyright (C) Nicola Bizzoca   2006  <hannibal_smith@users.sourceforge.net>
# Copyright (C) Simone Economo   2006  <ekoes@users.sourceforge.net>
# 
# Absynth  is free software.
# 
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 2 of the License, or (at your option)
# any later version.
# 
# main.py is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with main.py.  If not, write to:
#     The Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor
#     Boston, MA  02110-1301, USA.

import sys, platform, conf
import gtk
import raiseError

class HandleError:
	
	def __init__(self, errortype, exception, skipsearch = False):
		self.errortype 	= errortype
		self.exception 	= exception
		self.skipsearch = skipsearch
    
	def __writeBugReport(self):
		try:
			printStream = open ('bug-report.txt', 'w')
			printStream.write("OS: %s (%s) \n" 			% (platform.system(), platform.node()))
			printStream.write("Version: %s \n" 			% platform.version())
			printStream.write("Platform: %s \n" 		% platform.platform())           
			printStream.write("Python version: %s \n" 	% platform.python_version())        
			printStream.write("Exception: %s: %s \n" 	% (str(self.errortype), str(self.exception)))
			printStream.close()
            
		except IOError:
			print "Can't write to bug-report.txt. Have I permissions to write in my folders?"
	
	def __catchError(self):
		try:
			errorDialog = gtk.MessageDialog(None, 
				gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL, 
				gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, 
				message_format = conf.MSG_BOX_MESSAGE)
			errorDialog.run()
			errorDialog.destroy()
		except: pass
            
		self.__writeBugReport()
		sys.exit(1)
            
	def runError(self):
		type = self.errortype
		error = raiseError.RaiseError(self.errortype).search()
		instance = error(str(self.exception))
		self.errortype = not self.skipsearch and instance.__class__.__name__ or type
		#print self.skipsearch , instance.__class__.__name__ , type
		try:
			self.__catchError()
		except: 
			pass
		raise instance
		
def Invoker(klass):
    if not klass._instance:
        klass._instance = klass()
    return klass._instance